package com.atguigu.tingshu.user.pattern.impl;


import com.atguigu.tingshu.album.AlbumFeignClient;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.model.album.TrackInfo;
import com.atguigu.tingshu.model.user.UserPaidTrack;
import com.atguigu.tingshu.user.mapper.UserPaidTrackMapper;
import com.atguigu.tingshu.user.pattern.DeliveryStrategy;
import com.atguigu.tingshu.vo.user.UserPaidRecordVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Slf4j
@Component(SystemConstant.ORDER_ITEM_TYPE_TRACK)
public class TrackDelivery  implements DeliveryStrategy {

    @Autowired
    private AlbumFeignClient albumFeignClient;

    @Autowired
    private UserPaidTrackMapper userPaidTrackMapper;

    @Override
    public void delivery(UserPaidRecordVo userPaidRecordVo) {
        //根据type来判断用户买的是那种商品,是VIP还是专辑,还是声音

        Long userId = userPaidRecordVo.getUserId();

        String itemType = userPaidRecordVo.getItemType();

        String orderNo = userPaidRecordVo.getOrderNo();

        List<Long> itemIdList = userPaidRecordVo.getItemIdList();

        //走到这说明买的是声音
        //判断是否购买过声音

        TrackInfo trackInfo = albumFeignClient.getTrackInfo(itemIdList.get(0)).getData();
        Long albumId = trackInfo.getAlbumId();
        Long count = userPaidTrackMapper.selectCount(
                new LambdaQueryWrapper<UserPaidTrack>()
                        .eq(UserPaidTrack::getOrderNo, orderNo)
                        .select(UserPaidTrack::getId)
        );

        if (count > 0){
            return;
        }

        //走到这说明没处理过订单,保存订单
        //遍历id集合,批量导入
        for (Long trackId : itemIdList) {
            UserPaidTrack userPaidTrack = new UserPaidTrack();
            userPaidTrack.setUserId(userId);
            userPaidTrack.setOrderNo(orderNo);
            userPaidTrack.setAlbumId(albumId);
            userPaidTrack.setTrackId(trackId);

            userPaidTrackMapper.insert(userPaidTrack);
        }


    }
}
